package com.wangziyu.facerecognitiongate.adapter

import android.graphics.Canvas
import android.graphics.Paint
import androidx.recyclerview.widget.RecyclerView

/**
 * @description 树结构分界线
 * @author wzy
 * @date 2025/08/18 22:50:11
 */
class TreeItemDecoration(
    lineColor: Int = 0xFF888888.toInt(),
    lineWidth: Float = 4f,
    private val adapter: TreeAdapter
) : RecyclerView.ItemDecoration() {

    private val paint = Paint().apply {
        style = Paint.Style.STROKE
        color = lineColor
        strokeWidth = lineWidth
        isAntiAlias = true
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val layoutManager = parent.layoutManager ?: return
        val visibleNodes = adapter.getVisibleNodes()

        for (i in 0 until parent.childCount) {
            val childView = parent.getChildAt(i)
            val node = visibleNodes[i]

            node.parent?.let { parentNode ->
                val parentIndex = visibleNodes.indexOf(parentNode)
                if (parentIndex == -1) return@let
                val parentView = layoutManager.findViewByPosition(parentIndex) ?: return@let

                val startX = parentView.left + 30f
                val startY = parentView.top + parentView.height / 2f
                val endX = childView.left + 30f
                val endY = childView.top + childView.height / 2f

                // 先画一条竖线（父到子）
                c.drawLine(startX, startY, startX, endY, paint)
                // 再画一条横线（接到子节点）
                c.drawLine(startX, endY, endX, endY, paint)
            }
        }
    }
}